﻿using Wolfram.NETLink;
using System.Drawing;

namespace EmbeddedSharp.Scripting.Interfacing.Mathematica {
    public sealed class MathematicaKernel {

        private static MathematicaKernel kernel = new MathematicaKernel();

        // private Wolfram.NETLink.MathKernel mathKernel;
        private IKernelLink kl;

        private MathematicaKernel() {
          // this.mathKernel = new Wolfram.NETLink.MathKernel();

            // This launches the Mathematica kernel:
            kl = MathLinkFactory.CreateKernelLink();
            // Discard the initial InputNamePacket the kernel will send when launched.
            kl.WaitAndDiscardAnswer();
        }

        public static MathematicaKernel Instance {
            get {
                return kernel;
            }
        }

        public string Version {
            get {
                return kernel.Version;
            }
        }

        public string Evaluate(string expr) {
            //if (mathKernel.IsComputing) {
            //    mathKernel.Abort();
            //}

            //mathKernel.Compute(expr);
            //if (mathKernel.Graphics.Length > 0) {
            //    return (object) mathKernel.Graphics[0];
            //}

            //return mathKernel.Result;
            return kl.EvaluateToOutputForm(new Expr(expr), 120);
        }

        public Image EvaluateToImage(string expr) {
            return kl.EvaluateToImage(new Expr(expr), 800, 600);
        }
    }
}
